<?php

namespace IMT\UserBundle\Controller;

use IMT\UserBundle\Entity\Contact;

use IMT\UserBundle\Entity\User;

use IMT\UserBundle\Entity\Participant;
use IMT\AccountBundle\Form\AccountFormHandler;
use IMT\AccountBundle\Entity\Account;
use IMT\AccountBundle\Entity\AccountIMT;
use IMT\UserBundle\Entity\Group;
use IMT\AccountBundle\Form\AccountFormType;
use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\Request;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
 
class RegistrationController extends BaseController
{    
    public function registerAction(Request $request)
    {
    	/** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
    	$formFactory = $this->container->get('fos_user.registration.form.factory');
    	/** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
    	$userManager = $this->container->get('fos_user.user_manager');
    	/** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
    	$dispatcher = $this->container->get('event_dispatcher');
    
    	$user = $userManager->createUser();
    	$user->setEnabled(true);
    	
    	$em = $this->container->get('doctrine.orm.entity_manager');
    
    	$dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, new UserEvent($user, $request));
    
    	$form = $formFactory->createForm();
    	$form->setData($user);
    	$DataUser = $form->getData();
    	
    	if ('POST' === $request->getMethod()) {
    		$form->bind($request);
    
    		if ($form->isValid()) {
    			$event = new FormEvent($form, $request);
    			$dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
    
    			// Création du compte de base IMT
    			/*
    			$accountType = $this->container->get('doctrine')
    			->getEntityManager()
    			->getRepository('IMTAccountBundle:AccountIMT')
    			->find(intval($this->container->getParameter('default_account_id')));
    			*/ 		
    			
    			$user->setEmail($DataUser->getEmail());
    			$user->setUsername($DataUser->getUsername());
    			
    			$userManager->updateUser($user);
    			
    			$contact = new Contact();
    			$contact->setFirstname($request->request->get('firstname'));
    			$contact->setName($request->request->get('name'));
    			$contact->setCivility("Unknow");
    			$contact->setUser($user);
    			$contact->setEmail($user->getEmail());
    			
    			$contacts = $em->getRepository('IMTUserBundle:Contact')->findBy(array(
    				'email' => $contact->getEmail()
    			));
    			 
    			if(is_array($contacts) && sizeof($contacts) > 0){
    				foreach($contacts as $contactLink){
    					if($contactLink->getUser()){
    						$contactLink->setContactUser($contact);
    						 
    						$em->persist($contactLink);
    						$em->flush();
    					}
    				}
    			}
    			
    			$accountIMT = new AccountIMT();
    			$accountIMT->setTitle("Mon compte MyTime");
    			$accountIMT->setActive(true);
    			$accountIMT->setColor('fc-event-blue');
    			$accountIMT->setUser($user);
    			$accountIMT->addContact($contact);
    			
    			$em->persist($accountIMT);

    			$message = \Swift_Message::newInstance()
    			->setSubject('Bienvenue sur MyTime')
    			->setFrom('no-reply@my-time.fr')
    			->setTo('adrien.queriaud@gmail.com')
    			->setBody(
    					$this->container->get('templating')->renderResponse(
    							'IMTUserBundle:Mails:inscription.html.twig'
    					)->getContent()
    			);
    			$this->container->get('mailer')->send($message);
    
    			if (null === $response = $event->getResponse()) {
    				$url = $this->container->get('router')->generate('fos_user_registration_confirmed');
    				$response = new RedirectResponse($url);
    			}
    
    			$dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
    
    			return $response;
    		}
    	}
    
    	return new RedirectResponse($this->container->get('router')->generate('fos_user_security_login'));
//     	return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array(
//     			'form' => $form->createView(),
//     	));
    }
    

    
}
